package com.nut.lmsc.interceptor;

import com.nut.lmsc.common.Constants;
import com.nut.lmsc.common.FailMessage;
import com.nut.lmsc.common.Holder;
import com.nut.lmsc.common.Result;
import com.nut.lmsc.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class MerchantLoginInterceptor implements HandlerInterceptor {

    private static final String UNLOGIN = JacksonUtils.toJson(Result.fail(FailMessage.UNLOGIN));

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        log.info("preHandle_start" + System.currentTimeMillis());

        String token = request.getHeader(Constants.LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            writeFail(response);
            return false;
        }

        MerchantJwt merchantJwt = JwtTokenUtil.parseMerchantToken(token);

        if (merchantJwt == null || merchantJwt.getMobile() == null) {
            writeFail(response);
            return false;
        }

        //放入值
        Holder.MERCHANT_JWT_THREAD_LOCAL.set(merchantJwt);

        return true;
    }

    private void writeFail(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(Constants.CONTENT_TYPE);
        PrintWriter printWriter = response.getWriter();
        printWriter.write(UNLOGIN);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //移除值
        Holder.MERCHANT_JWT_THREAD_LOCAL.remove();
    }

    public static void main(String[] args) {
        System.out.println(JacksonUtils.toJson(Result.fail(FailMessage.UNLOGIN)));
    }
}
